package jsf.uss.beans;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.inject.Inject;

import jsf.uss.controllers.ClientController;
import jsf.uss.data.IOrderRepository;
import jsf.uss.data.IRepository;
import jsf.uss.models.Client;
import jsf.uss.models.Order;

@ManagedBean(name = "orderBean")
@RequestScoped
public class OrderBean implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = -3195830106176149289L;

    @Inject
    public IOrderRepository orderRepository;
    public Order order = new Order();
    public Client client = new Client();

    public OrderBean() {
    }

    public Order getOrder() {
	return order;
    }

    public void setOrder(Order order) {
	this.order = order;
    }

    public Client getClient() {
	return client;
    }

    public void setClient(Client client) {
	this.client = client;
    }

    public Client getClient(Long id) {
	IRepository<Client> clientRepository = new ClientController();

	this.client = clientRepository.getById(id);
	this.setClient(client);

	return client;
    }

    public List<Order> getAllOrders() {
	return orderRepository.getAll();
    }

    public Order getOrderById(Long id) {
	this.order = orderRepository.getById(id);

	return this.order;
    }

    public void create() {
	this.order = new Order();
    }

    public void add() {
	BigDecimal orderPrice = this.order.getPricePerItem().multiply(
		new BigDecimal(this.order.getQuantity()));
	this.order.setOrderPrice(orderPrice);
	this.order.setClient(this.client);
	orderRepository.add(this.order);
    }

    public void update() {
	BigDecimal orderPrice = this.order.getPricePerItem().multiply(
		new BigDecimal(this.order.getQuantity()));
	this.order.setOrderPrice(orderPrice);
	orderRepository.update(this.order);
    }

    public void delete(Long id) {
	orderRepository.remove(id);
    }

    public void delete() {
	orderRepository.remove(this.order);
    }

    public String getOrders(Long id) {
	this.client = getClient(id);

	return "ClientOrders.xhtml?faces-redirect=true";
    }

    public List<Order> getOrdersForClient() {
	List<Order> result = orderRepository.getAllOrdersForClient(client
		.getClientId());

	return result;
    }
}
